<template>
    <el-dialog
      :visible.sync="visible"
      :title="dataForm.details ? '详情' : !dataForm.id ? $t('add') : $t('update')"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmitHandle()"
        :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
        :disabled="disabled"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="范围" prop="type">
                <el-select
                clearable
                v-model="dataForm.typeIds"
                multiple

                >
                <el-option
                    v-for="role in typeList"
                    :key="role.id"
                    :label="role.name"
                    :value="role.id"
                ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="dataForm.name" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠券数量" prop="limitNum">
              <el-input type="number" v-model="dataForm.limitNum" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抵扣金额" prop="price">
              <el-input type="number" v-model="dataForm.price" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抵扣起始值" prop="validPrice">
              <el-input type="number" v-model="dataForm.validPrice" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="expireTime">
              <el-input type="number" v-model="dataForm.expireTime" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item  label="领取时间" prop="time">
              <el-date-picker
                :picker-options="pickerOptions"
                v-model="value1"
                type="datetimerange"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="使用规则" prop="useRule">
                <el-input
                  v-model="dataForm.useRule"
                  placeholder=""
                  type="textarea"
                  :rows="5"
                ></el-input>
              </el-form-item>
            </el-col>
        </el-row>
        
      </el-form>
      <template slot="footer" v-if="!disabled">
        <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{
          $t("confirm")
        }}</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script>
  import Cookies from "js-cookie";
  import debounce from "lodash/debounce";
  export default {
    data() {
      return {
        visible: false,
        sizes:[
            "750*400px",
            "750*274px",
            "750*420px",
            "750*420px",
            "750*610px",
            "750*420px",
            "702*380px",
            "750*320px",
            "750*320px",
            "750*580px",
            "750*450px",
            "750*450px",
            "750*450px",
            "750*450px",
            "750*450px",
            "750*450px",
            "750*450px",
            "750*970px",
            "522*738px",
            "750*420px",
            "750*500px",
            "750*801px"
          ],
        url: `${
          window.SITE_CONFIG["apiURL"]
        }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
        fileList: [],
        dataForm: {
          id: "",
          name: "",
          type: "",
          price: "",
          validPrice: "",
          validStart:"",
          validEnd:"",
          typeIds:"",
          useRule:"",
          limitNum:"",
          expireTime:""
        },
        pickerOptions: {
          onPick: ({ maxDate, minDate }) => {
            this.choiceDate = minDate.getTime();
            if (maxDate && maxDate.getTime() > new Date().getTime()) {
              this.choiceDate = "";
            }
          },
          // disabledDate: (time) => {
          //   const today = new Date();
          //   const one = 90 * 24 * 3600 * 1000; // 30天
          //   today.setHours(0, 0, 0, 0);
          //   const maxTime =
          //     today.getTime() > this.choiceDate + one
          //       ? this.choiceDate + one
          //       : today.getTime();
          //   if (this.choiceDate) {
          //     const minTime = this.choiceDate - one;
          //     return time.getTime() < minTime || time.getTime() > maxTime;
          //   }
          //   return time.getTime() > maxTime;
          // },
        },
        value1: [],
        
      };
    },
    props: {
      disabled: Boolean,
      typeList: Array
    },
  
    computed: {
      dataRule() {
        return {
          name: [
            {
              required: true,
              message: this.$t("validate.required"),
              trigger: "blur",
            },
          ],
        };
      },
    },
    mounted(){
        console.log(this.typeList)
    },
    watch: {
        visible(newval){
            console.log(newval)
            if(!newval){
                this.dataForm.typeIds = []
            }
        },
      value1(newval, oldval) {
        if (newval != oldval&&newval) {
          this.dataForm.validStart = newval[0];
          this.dataForm.validEnd = newval[1];
        } else {
          this.dataForm.validStart = "";
          this.dataForm.validEnd = "";
        }
      },
    },
    methods: {

      // 上传之前
      beforeUploadHandle(file) {
        if (
          file.type !== "image/jpg" &&
          file.type !== "image/jpeg" &&
          file.type !== "image/png" &&
          file.type !== "image/gif"
        ) {
          this.$message.error(
            this.$t("upload.tip", {
              format: "jpg、png、gif",
            })
          );
          return false;
        }
      },
      // 上传成功
      successHandle1(res, file, fileList, index) {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        console.log(index);
        this.dataForm.bannerList[index].path = res.data.url;
        console.log(this.dataForm.bannerList[index]);
      },
      init() {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            this.getInfo();
          }else{
            this.value1 = "";
            for (let key in this.dataForm) {
              this.dataForm[key] = ""; // 将对象中的每个属性赋为空值
            }
            console.log(this.dataForm)
          }
        });
      },
      addBanner() {
        this.dataForm.bannerList.push({
          linkUri: "",
          path: "",
          sort: "",
          type: "",
        });
      },
      delBanner(index) {
        this.dataForm.bannerList.splice(index, 1);
      },
      // 获取信息
      getInfo() {
        this.$http
          .get("/sys/discountCoupon/ " + this.dataForm.id)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            }
            this.dataForm = {
              ...this.dataForm,
              ...res.data,
            };
            if(this.dataForm.typeIds){
                this.dataForm.typeIds = this.dataForm.typeIds.split(',');
                this.dataForm.typeIds = this.dataForm.typeIds.map(str => parseFloat(str));
                console.log(this.dataForm.typeIds)
            }
            if(this.dataForm.validStart && this.dataForm.validEnd){
              this.value1 = [this.dataForm.validStart, this.dataForm.validEnd];
            }else{
              this.value1 = ""
            }
            
            console.log(this.value1)
          })
          .catch(() => {});
      },
      // 表单提交
      dataFormSubmitHandle: debounce(
        function () {
          this.$refs["dataForm"].validate((valid) => {
            if (!valid) {
              return false;
            }
            if(this.dataForm.typeIds){
              this.dataForm.typeIds = this.dataForm.typeIds.join(',')
            }
           
            this.$http[!this.dataForm.id ? "post" : "put"](
              "/sys/discountCoupon",
              this.dataForm
            )
              .then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg);
                }
                this.$message({
                  message: this.$t("prompt.success"),
                  type: "success",
                  duration: 500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              })
              .catch(() => {});
          });
        },
        1000,
        {
          leading: true,
          trailing: false,
        }
      ),
    },
  };
  </script>
  
  <style scoped lang="scss">
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
  
      .el-upload:hover {
        border-color: #409eff;
      }
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 140px;
      height: 140px;
      line-height: 140px;
      text-align: center;
    }
  
    .avatar {
      width: 140px;
      height: 140px;
      display: block;
    }
  
    .el-upload-list__item {
      width: 140px;
      height: 140px;
    }
  
    .el-upload.el-upload--picture-card {
      width: 140px;
      height: 140px;
      line-height: 140px;
    }
  }
  
  .picDiv {
    .el-form-item__content {
      .item {
        text-align: center;
        display: grid;
        grid-template-columns: 200px auto auto auto 50px;
        gap: 0 14px;
      }
    }
  }
  </style>
  